package com.kingdee.shr.custom.handler.examinscore;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.workflow.WfException;
import com.kingdee.bos.workflow.service.EnactmentServiceProxy;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.IPositionMember;
import com.kingdee.eas.custom.examinscore.ExaminscoresInfo;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.ats.web.util.SHRBillUtil;
import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.shr.custom.handler.atsexception.AtsExceptiontionBillListHandler;
import com.kingdee.util.DateTimeUtils;
import com.kingdee.util.StringUtils;

/**
 * Title: ExaminScoreHandler.java
 * @Copyright 版权所有：天津金蝶软件有限公司 <br>     
 *  Description: 考勤异常单-Web端
 * @author 杨旭东 Email:tjyangxudong@kingdeecom
 * @date 2019-8-6
 * @version 1.0
 */
public class ExaminScoreHandler extends EditHandler {
    private static Logger logger = Logger.getLogger(AtsExceptiontionBillListHandler.class);

    private Context ctx;

    private IPositionMember iPositionMember;

    StringBuffer sql = new StringBuffer();

    public ExaminScoreHandler(Context ctx) {
        this.ctx = ctx;
    }

    public ExaminScoreHandler() {
        this.ctx = SHRContext.getInstance().getContext();
    }

    /**
     * 
     * <p>
     * Title: canSubmitEffectAction
     * </p>
     * <p>
     * Description:判断能否提交
     * </p>
     * 
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */

    @SuppressWarnings("unchecked")
    public void canSubmitEffectAction(HttpServletRequest request, HttpServletResponse response,
            ModelMap modelMap) throws SHRWebException {
        Map map = new HashMap();
        map.put("state", "success");
        JSONUtils.writeJson(response, map);

    }

    /**
     * 
     * <p>
     * Title: getJobInfoAction
     * </p>
     * <p>
     * Description:获取被审核人岗位
     * </p>
     * 
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    @SuppressWarnings("unchecked")
    public void getJobInfoAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
            throws SHRWebException {
        String personId = request.getParameter("personId");
        String sql = getQuerySql(personId);
        String jobId = null;
        String jobName = null;
        IRowSet rowSet = null;
        Map map = new HashMap();
        Map job = new HashMap();
        try {
            rowSet = DbUtil.executeQuery(this.ctx, sql);
            while (rowSet.next()) {
                jobId = rowSet.getString("jobId");
                jobName = rowSet.getString("jobName");

                job.put("id", jobId);
                job.put("name", jobName);
                map.put("job", job);
            }

        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException("获取该员工的岗位信息失败！" + e);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ShrWebBizException("获取该员工的岗位信息失败！" + e);
        }
        JSONUtils.SUCCESS(map);
    }

    /**
     * 
     * <p>
     * Title: getAssessmentIndexsAction
     * </p>
     * <p>
     * Description: 根据部门查询负面清单项目
     * </p>
     * 
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */

    public void getProjectAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
            throws SHRWebException {
        Map<String,List<Map<String,String>>> result = new HashMap<String, List<Map<String,String>>>();
        String orgId = ContextUtil.getCurrentAdminUnit(ctx).getId().toString();
        result.put("orgIds", buildExamItemList(orgId));
        writeSuccessData(result);
    }

   

    /**
     * （非 Javadoc）
     * <p>
     * Title: beforeSubmit
     * </p>
     * <p>
     * Description: 提交工作流
     * </p>
     * 
     * @param request
     * @param response
     * @param model
     * @throws SHRWebException
     * @see com.kingdee.shr.base.syssetting.web.handler.EditHandler#beforeSubmit(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, com.kingdee.eas.framework.CoreBaseInfo)
     */
    @Override
    protected void beforeSubmit(HttpServletRequest request, HttpServletResponse response, CoreBaseInfo model)
            throws SHRWebException {
        super.beforeSubmit(request, response, model);

        ExaminscoresInfo bill = (ExaminscoresInfo) model;

        String userID = HRFilterUtils.getCurrentUserId(ctx);
        String functionName = "com.kingdee.eas.custom.examinscore.app.ExaminscoresEditUIFunction";
        String operationName = "actionSubmit";
        try {
            String temp = EnactmentServiceProxy.getEnacementService(ctx).findSubmitProcDef(userID, bill,
                    functionName, operationName);
            if ((temp == null) || (temp.trim().equals("")))
                throw new ShrWebBizException("没有可用的考核评分工作流");
        } catch (WfException e) {
            throw new SHRWebException(e.getMessage());
        } catch (BOSException e) {
            throw new SHRWebException(e.getMessage());
        }

        bill.setBillState(HRBillStateEnum.SUBMITED);
        String operateStatus = request.getParameter("operateState");
        if ((StringUtils.isEmpty(operateStatus)) || (!("ADDNEW".equalsIgnoreCase(operateStatus)))) {
            return;
        }
        bill.setExtendedProperty("isAddNew", "isAddNew");
    }

    /**
     * （非 Javadoc）
     * <p>
     * Title: afterCreateNewModel
     * </p>
     * <p>
     * Description: 带出提交人部门、创建数据时间
     * </p>
     * 
     * @param request
     * @param response
     * @param coreBaseInfo
     * @throws SHRWebException
     * @see com.kingdee.shr.base.syssetting.web.handler.EditHandler#afterCreateNewModel(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, com.kingdee.eas.framework.CoreBaseInfo)
     */
    protected void afterCreateNewModel(HttpServletRequest request,
            HttpServletResponse response, CoreBaseInfo coreBaseInfo)
            throws SHRWebException {
           super.afterCreateNewModel(request, response, coreBaseInfo);

           Date nowDate = DateTimeUtils.truncateDate(new Date());
           UserInfo currentUserInfo = ContextUtil.getCurrentUserInfo(this.ctx);
           ExaminscoresInfo info = (ExaminscoresInfo) coreBaseInfo;
           BOSUuid userId = currentUserInfo.getPerson().getId();
           PersonPositionInfo personPositionInfo = SHRBillUtil.getAdminOrgUnit(userId.toString());
           info.setCreator(currentUserInfo);
           info.setBizDate(nowDate);
           info.setAdminOrg(personPositionInfo.getPersonDep());

          }

    /**
     * 
     * <p>
     * Title: getQuerySql
     * </p>
     * <p>
     * Description: 查询人员岗位
     * </p>
     * 
     * @param personId
     * @return
     */
    private String getQuerySql(String personId) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT pos.fid jobId,pos.fname_l2 as jobName FROM T_BD_PERSON person");
        sql.append("  left join  T_HR_PersonPosition pp on person.fid=pp.fpersonid ");
        sql.append(" left join T_ORG_POSITION  pos on pp.fprimarypositionid=pos.fid ");
        sql.append("left join T_ORG_POSITIONMEMBER personStion on person.fid=personStion.fpersonid");
        sql.append(" where personStion.FISPRIMARY =1   ");
        sql.append("  and person.fid='" + personId + "'");
        logger.info("查询岗位" + personId + "SQL" + sql.toString());
        return sql.toString();
    }
    
    /**
     * <p>Title: buildExamItemList</p>
     * <p>Description:构建负面清单项List </p>
     * @param orgId
     * @return 负面清单List
     * @throws ShrWebBizException
     */
    private List<Map<String, String>> buildExamItemList(String orgId) throws ShrWebBizException {
        List< Map <String,String>> examinItemList=new ArrayList<Map<String,String>>();
        //String project=null;
        //String standard=null;
        if (!StringUtils.isEmpty(orgId)) {
            String sql = " SELECT cma.fname_l2 AS project,cdd.FDescription AS standard " +
            		" FROM " +
            		" CT_DEP_DeptWorklistEntry cdd " +
            		" LEFT JOIN  CT_DEP_DeptWorklist wok on cdd.fbillid=wok.fid " +
            		" LEFT JOIN " +
            		" CT_MAN_AssessmentIndexs cma " +
            		" ON " +
            		" cdd.CFNegativeListItem=cma.Fid " +
            		" WHERE " +
            		" wok.fbillstate=3 AND cdd.FAdminOrgID='"+orgId+"'";
            System.out.println("获取符合当前登录人部门的负面清单:" + sql);
            try {
                IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
                while (rowSet.next()) {
                    Map <String,String> examinItem=new HashMap<String,String>();                   
                    examinItem.put("project",rowSet.getString("project") );
                    examinItem.put("standard",rowSet.getString("standard") );
                    examinItemList.add(examinItem);
                }
            } catch (BOSException e) {
                e.printStackTrace();
                throw new ShrWebBizException("根据部门查询负面清单项目和评价标准失败！");
              } catch (SQLException e) {
                e.printStackTrace();
                throw new ShrWebBizException("根据部门查询负面清单项目和评价标准为空！");
                }
            }
        return examinItemList;
    }

    /**
     * @param iPositionMember the iPositionMember to set
     */
    public void setIPositionMember(IPositionMember iPositionMember) {
        this.iPositionMember = iPositionMember;
    }

    /**
     * @return the iPositionMember
     */
    public IPositionMember getIPositionMember() {
        return iPositionMember;
    }
}
